package cn.com.utils;

import cn.com.spring.aspecti.AspectProxy;
import cn.com.spring.handler.AsyncProxy;
import cn.com.spring.handler.CglibProxy;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;

/**
 * bean工具类
 *
 * @author LiuGuodong
 * @date 2024/01/26
 */
public class AopUtil {

    /**
     * 获取通用代理
     *
     * @param tClass t类
     * @return {@link T}
     * @throws InstantiationException 实例化异常
     * @throws IllegalAccessException 非法访问异常
     */
    public static <T> T getCurrencyProxy(Class<T> tClass) throws InstantiationException, IllegalAccessException {
        return getProxy(tClass, new CglibProxy(tClass.newInstance()));
    }

    /**
     * 获取异步代理
     *
     * @param tClass t类
     * @return {@link T}
     * @throws InstantiationException 实例化异常
     * @throws IllegalAccessException 非法访问异常
     */
    public static <T> T getAsyncProxy(Class<T> tClass) throws InstantiationException, IllegalAccessException {
        return getProxy(tClass, new AsyncProxy());
    }

    /**
     * 获取切面代理
     *
     * @param tClass t类
     * @return {@link T}
     * @throws InstantiationException 实例化异常
     * @throws IllegalAccessException 非法访问异常
     */
    public static <T> T getAspectProxy(Class<T> tClass) throws InstantiationException, IllegalAccessException {
        return getProxy(tClass, new AspectProxy(tClass.newInstance()));
    }


    /**
     * 获取代理
     *
     * @param tClass t类
     * @return {@link T}
     * @throws InstantiationException 实例化异常
     * @throws IllegalAccessException 非法访问异常
     */
    public static <T> T getProxy(Class<T> tClass, Callback callback) throws InstantiationException, IllegalAccessException {
        Enhancer enhancer = new Enhancer();
        // 设置需要代理的对象
        enhancer.setSuperclass(tClass);
        // 设置代理人
        enhancer.setCallback(callback);
        return (T) enhancer.create();
    }
}
